import * as readline from 'readline';
import { ChatManager } from '../core/chat';
import { CommandManager } from './commands';
import { modelManager } from '../core/models'; 
import { CLIStreamHandler } from './cli-stream-handler';
import { HistorySaver } from './history-saver';
import { configManager } from '../utils/config';

export class CLI {
  private rl: readline.Interface;
  private chatManager: ChatManager;
  private commandManager: CommandManager;
  private streamHandler: CLIStreamHandler;
  private historySaver: HistorySaver;

  constructor() {
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    // 创建历史保存管理器
    this.historySaver = new HistorySaver(true); // 默认启用

    // 创建流事件处理器
    this.streamHandler = new CLIStreamHandler({ debugMode: false });
    // 使用组合模式：创建独立的工具管理器并注入到聊天管理器
 
    this.chatManager = new ChatManager(this.streamHandler);
    
    // 从配置文件连接启用的 MCP 服务器
    this.connectMCPServers();
      
    this.commandManager = new CommandManager();

      // 监听对话完成事件
      this.streamHandler.onConversationComplete = () => {
        this.showUsageInfo(); // 添加usage信息显示
        console.log('\n=== 🎉 对话完成 ===\n');
      };
  }


  // 从配置连接 MCP 服务器
  private async connectMCPServers() {
    const enabledServers = configManager.getEnabledMCPServers();
    
    if (enabledServers.length === 0) {
      console.log('📡 未配置启用的 MCP 服务器');
      return;
    }

    console.log(`📡 正在连接 ${enabledServers.length} 个 MCP 服务器...`);
    
    for (const server of enabledServers) {
      try {
        console.log(`🔗 连接到 ${server.name}...`);
        const success = await this.chatManager.connectMCPServer(
          server.name, 
          server.command, 
          server.cwd
        );
        
        if (success) {
          console.log(`✅ ${server.name} 连接成功`);
        } else {
          console.log(`❌ ${server.name} 连接失败`);
        }
      } catch (error) {
        console.error(`❌ ${server.name} 连接错误:`, error);
      }
    }
  }

  start() {
    this.showWelcome();
    this.askQuestion();
  }

  private showWelcome() {
    console.log('=== 🤖 AI 对话系统 v2.0 (事件驱动架构) ===');
    console.log('🔧 支持工具调用的智能助手（通过提示词实现）');
    
    const currentModel = modelManager.getCurrentModel();
    const toolCount = this.chatManager.getToolManager().getToolCount();
    
    console.log(`📱 当前模型: ${currentModel.name}`);
    console.log(`🛠️  可用工具: ${toolCount} 个`);
    
    console.log('\n💡 输入 /help 查看可用命令');
    console.log('💬 直接输入问题开始对话');
    console.log('🔧 AI 会自动判断是否需要调用工具');
    console.log('🐛 输入 /debug 切换调试模式\n');
  }
  private askQuestion() {
    this.rl.question('🗣️  请输入您的问题: ', async (answer) => {
      if (!answer.trim()) {
        this.askQuestion();
        return;
      }

      // 清除用户输入行（美化显示）
      process.stdout.write('\x1b[1A\x1b[2K');
      console.log(`🗣️  ${answer}`);
      
      try {
        // 检查是否是命令
        const isCommand = await this.commandManager.executeCommand(answer, this.chatManager, this);
        if (!isCommand) {
          // 不是命令，发送给AI
          await this.chatManager.sendMessage(answer);
          // ChatManager会自动保存历史，不需要手动保存
        }
      } catch (error) {
        console.error(`\n❌ 处理失败: ${error instanceof Error ? error.message : '未知错误'}`);
      }
      // 继续对话
      this.askQuestion();
    });
  }

    private showUsageInfo() {
      const lastUsage = this.chatManager.getLastUsage();
      if (lastUsage) {
        console.log(`📊 Usage: ${lastUsage.prompt_tokens} prompt + ${lastUsage.completion_tokens} completion = ${lastUsage.total_tokens} total tokens`);
      }
    }

  stop() {
    // 程序结束时不需要手动保存，ChatManager已自动保存
    this.rl.close();
  }

    // 公开方法供外部使用
    getChatManager(): ChatManager {
      return this.chatManager;
    }

    getCommandManager(): CommandManager {
      return this.commandManager;
    }

    getStreamHandler(): CLIStreamHandler {
      return this.streamHandler;
    }

    getHistorySaver(): HistorySaver {
      return this.historySaver;
    }

    // 切换调试模式
    toggleDebugMode(): boolean {
      const newMode = !this.streamHandler.getDebugMode();
      this.streamHandler.setDebugMode(newMode);
      console.log(`🐛 调试模式: ${newMode ? '已开启' : '已关闭'}`);
      return newMode;
    }

    // 切换历史保存
    toggleHistorySaving(): boolean {
      const currentEnabled = this.historySaver.getSessionId() !== '';
      this.historySaver.setEnabled(!currentEnabled);
      return !currentEnabled;
    }

    // 显示历史记录列表
    showHistoryList() {
      const historyFiles = this.historySaver.listHistoryFiles();
      if (historyFiles.length === 0) {
        console.log('📂 没有找到历史记录文件');
        return;
      }

      console.log('\n=== 📚 历史记录列表 ===');
      historyFiles.forEach((file, index) => {
        console.log(`${index + 1}. ${file}`);
      });
      console.log('===================\n');
    }
  }

// 处理程序退出
process.on('SIGINT', () => {
  console.log('\n\n=== 👋 再见! ===');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n\n=== 👋 再见! ===');
  process.exit(0);
});
